<?php


namespace App\Http\Middleware;

use App\Models\Adminer\RoleMenu;
use App\Models\Adminer\Admins;
use App\Http\Controllers\Controller;
use Closure;

class AdminMust extends Controller
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  \App\Models\Adminer\Admins $admins
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $adminer = $this->authAdmin();
        if(!$adminer) {
            return response($this->error('登录过期请重新登录',203));
        }

//        if($adminer->enable !== 1) {
//            return response($this->error('管理员已被禁封', 204));
//        }

        self::$authAdmin = $adminer;

        // TODO 菜单权限验证
        if(in_array($request->path(), [ // 过滤不需要 验证权限的接口
            'admin/user-info', 'admin/adminer-menus', 'admin/logout',
            'admin/project-cate-all', 'admin/project-all', 'admin/product-all', 'admin/module-all',
            'admin/host-env-all', 'admin/host-all', 'admin/cheader-all', 'admin/random-check-module-all','admin/api-all',
            'admin/param-view-res', 'admin/more-sample-values'
        ])) {
            return $next($request);
        }

        if($adminer->name == 'admin') {
            return $next($request);
        }

        $path = $request->path();
        if(!RoleMenu::isPermission($adminer->role_id, $path)){
            return response($this->error('没有相关权限',402));
        }

        return $next($request);
    }

    public function terminate($request, $response){
        self::$authAdmin = null;
    }

}
